package logic

import (
	"context"
	"pro-train-hub/models/mysql"

	"pro-train-hub/trainrpc/internal/svc"
	"pro-train-hub/trainrpc/trainrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LessonsListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLessonsListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LessonsListLogic {
	return &LessonsListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LessonsListLogic) LessonsList(in *trainrpc.LessonsListRequest) (*trainrpc.LessonsListResponse, error) {
	// todo: add your logic here and delete this line
	var lists []mysql.LessonData
	tx := mysql.DB.Debug().
		Model(&mysql.Lesson{}).
		Select("lessons.*,users.username,users.avatar").
		Joins("left join users on users.id = lessons.user_id").
		Scopes(mysql.Paginate(int(in.Page), int(in.Size)))
	if in.TitleSearch != "" {
		tx.Where("title like ?", "%"+in.TitleSearch+"%")
	}
	if in.AreaSearch != "" {
		tx.Where("area = ?", in.AreaSearch)
	}
	if in.Order == "" {
		tx.Order("lessons.created_at asc")
	} else if in.Order == "desc" {
		tx.Order("lessons.created_at desc")
	}

	tx.Find(&lists)
	var listData []*trainrpc.LessonsList
	for _, list := range lists {
		lessonsList := trainrpc.LessonsList{
			Info:     list.Info,
			Area:     list.Area,
			Picture:  list.Picture,
			Title:    list.Title,
			Price:    list.Price,
			Username: list.Username,
			Avatar:   list.Avatar,
		}
		listData = append(listData, &lessonsList)
	}
	var total int64
	mysql.DB.Debug().Model(&mysql.Lesson{}).Count(&total)
	return &trainrpc.LessonsListResponse{
		List:  listData,
		Total: total,
	}, nil
}
